<?php
namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\Mvc\MvcEvent;
use Zend\Authentication\AuthenticationService;
use Application\Model\Dao\UserDao;
use Zend\Session\Container;

class LoginAwareController extends AbstractActionController
{

    public function onDispatch(MvcEvent $e)
    {
        $auth = new AuthenticationService();
        if ($auth->hasIdentity()) {
            parent::onDispatch($e);
        } else {
            if ($this->getEvent()->getParam("ajax")) {
                $this->redirect()->toUrl("/loginAjax");
            } else {
                $this->redirect()->toUrl("/login");
            }
        }
    }
    
    protected function getLoggedinUserId()
    {
        $auth = new AuthenticationService();
        if ($auth->getIdentity()) {
            $commentor = $auth->getIdentity()->id;
            return $commentor;
        }
        return 0;
    }
    
    protected function getUserFromSession(){
    	$auth = new AuthenticationService();
    	$userSession = new Container('user');

    	if($userSession->user == null){
            $userSession->user = $this->updateIdentity();
    	}
        return $userSession->user;
    }
    
    
    protected function updateIdentity(){
    	$loggedInId = $this->getLoggedinUserId();
    	$userSession = new Container('user');
    	if($loggedInId != 0) {
    		$userDao = new UserDao();
    		$user = $userDao->getUserByIdWithGroup($loggedInId);

    		$userSession->user = $user;
            return $user;
    	}
    }


    protected function getUsersGroup(){
        $loggedInGouppIdsId = array();
        $curUser = $this->getUserFromSession();
        $groups = $curUser->groups;
        if($groups){
            foreach($groups as $group ){
                array_push($loggedInGouppIdsId, $group['id']);
            }
        }

        return $loggedInGouppIdsId;

    }

    protected function getUsersApartmentId(){
        $loggedInGouppIdsId = array();
        $curUser = $this->getUserFromSession();
        $groups = $curUser->groups;
        if($groups){
            foreach($groups as $group ){
                if($group['type'] === 'apartment') {
                    return $group['id'];
                }
            }
        }
    }

    protected function getUsersBlockId(){
        $loggedInGouppIdsId = array();
        $curUser = $this->getUserFromSession();
        $groups = $curUser->groups;
        if($groups){
            foreach($groups as $group ){
                if($group['type'] === 'block') {
                    return $group['id'];
                }
            }
        }
    }
   
}

?>